package com.xoa.plugin;

import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.dao.flowhook.FlowHookMapper;
import com.xoa.dao.notify.NotifyMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.global.proxy.TriggerSubject;
import com.xoa.model.common.SysPara;
import com.xoa.model.document.DocumentModel;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.notify.Notify;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowHookWithBLOBs;
import com.xoa.model.workflow.FlowRun;
import com.xoa.model.workflow.TriggerPlugIn;
import com.xoa.service.document.DocumentSerivce;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.file.WordHtml;
import com.xoa.util.http.HttpClientUtil;
import net.sf.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 创建作者: 刘建
 * 创建日期: 2020-06-22 14:52
 * 方法介绍: 转发公告插件
 */
@Service
public class NotifyTrigger implements TriggerSubject {
    @Autowired
    private FlowHookMapper flowHookMapper;
    @Autowired
    private NotifyMapper notifyMapper;
    @Autowired
    private FlowRunMapper flowRunMapper;
    @Autowired
    private DocumentSerivce documentSerivce;
    @Autowired
    private AttachmentMapper attachmentMapper;
    @Autowired
    private SysParaMapper sysParaMapper;

    @Override
    public void doRun(String company, Object... ags) {
        ContextHolder.setConsumerType(company);
        TriggerPlugIn tri = (TriggerPlugIn) ags[0];
        Notify notify = new Notify();
        if (tri.getNotifyId() != null) {
            notify.setNotifyId(tri.getNotifyId());
            FlowHookWithBLOBs flowHookNew = new FlowHookWithBLOBs();
            flowHookNew.setHid(tri.getHookId());
            //获取对照关系
            FlowHookWithBLOBs flowHook = flowHookMapper.selectByhid(flowHookNew);
            Map<Object, Object> flowHookMaps = null;
            if (flowHook != null) {
                flowHookMaps = FlowHtmlUtil.queryTriggerField(tri.getModify(), tri.getReject(), flowHook.getMap(), flowHook.getDataDirection());
            }
            //文件上传路径
            StringBuilder uploadHead = FileUploadUtil.getUploadHead();
            notify.setSendTime(new Date());
            Users users = tri.getUsers();
            Date curDate = new Date(System.currentTimeMillis());
            notify.setFromId(users.getUserId());
            notify.setFromDept(users.getDeptId());
            notify.setLastEditTime(curDate);
            notify.setLastEditor(users.getUserId());
            notify.setBeginDate((int) (System.currentTimeMillis() / 1000));
            notify.setSubject("[无主题]");
            // 当前年月
            String ym = new SimpleDateFormat("yyMM").format(new Date());
            StringBuilder newFilePathBd = uploadHead;
            newFilePathBd.append(System.getProperty("file.separator")).
                    append(company).append(System.getProperty("file.separator")).
                    append("notify").append(System.getProperty("file.separator")).append(ym);
            //获得模块id
            byte mid = 0;
            for (ModuleEnum em : ModuleEnum.values()) {
                if (em.getName().equals("notify")) {
                    mid = (byte) em.getIndex();
                }
            }
            List<Attachment> attachmentListNew = new ArrayList<>();
            //获取公共附件
            FlowRun flowRun = flowRunMapper.selectByRunId(Integer.valueOf(tri.getRunId()));
            String attachmentId = flowRun.getAttachmentId();
            String attachmentName = flowRun.getAttachmentName();
            List<Attachment> attachmentList = GetAttachmentListUtil.returnAttachment(attachmentName, attachmentId, company, "workflow");
            List<File> files = new ArrayList<File>();
            // 循环添加
            for (int i = 0, length = attachmentList.size(); i < length; i++) {
                Attachment attachment = attachmentList.get(i);
                StringBuilder flowFilePath = FileUploadUtil.getUploadHead();
                flowFilePath.append(System.getProperty("file.separator")).
                        append(company).append(System.getProperty("file.separator")).
                        append("workflow").append(System.getProperty("file.separator")).append(attachment.getYm()).
                        append(System.getProperty("file.separator")).append(attachment.getAttachId()).append(".").append(attachment.getAttachName());
                File file = new File(flowFilePath.toString());
                if (file.exists()) {
                    files.add(file);
                }
            }
            String depPath = null;
            //获取公文正文作为公告内容
            List<Attachment> fathAttach = new ArrayList<Attachment>();//先设置空的正文
            //获取父公文实体类
            DocumentModel fathDocument = documentSerivce.checkRunId(Integer.valueOf(tri.getRunId()));

            if (fathDocument!=null){
                //获取父公文的正文
                if (StringUtils.checkNull(fathDocument.getMainAipFile())) {//判断api为空
                    fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainFileName(), fathDocument.getMainFile(), company, "document");
                } else {
                    fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainAipFileName(), fathDocument.getMainAipFile(), company, "document");
                }
            }

            for (Attachment attachment : fathAttach) {
                StringBuilder flowFilePath = FileUploadUtil.getUploadHead();
                flowFilePath.append(System.getProperty("file.separator")).
                        append(company).append(System.getProperty("file.separator")).
                        append("document").append(System.getProperty("file.separator")).append(attachment.getYm()).
                        append(System.getProperty("file.separator")).append(attachment.getAttachId()).append(".").append(attachment.getAttachName());
                File file = new File(flowFilePath.toString());
                if (file.exists()) {
                    depPath = flowFilePath.toString();
                    files.add(file);
                }
            }

            //转存附件到公告
            for (File file : files) {
                String oldFileName = file.getName();
                //去掉文件旧的时间戳,因为所有的附件都是转存过来的 所以都存在时间戳
                oldFileName = oldFileName.substring(oldFileName.indexOf(".") + 1);
                byte[] buf = new byte[1024];
                int attachIDs = Math.abs((int) System.currentTimeMillis());
                String FName = attachIDs + "." + oldFileName;
                String FilePath = newFilePathBd + System.getProperty("file.separator") + FName;
                File omkFile = new File(newFilePathBd.toString());
                if (!omkFile.exists()) {
                    omkFile.mkdirs();
                }
                try (FileOutputStream out = new FileOutputStream(new File(FilePath)); FileInputStream in = new FileInputStream(file)) {
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                File newFile = new File(FilePath);
                if (newFile.exists()) {
                    Attachment attachment = new Attachment();
                    attachment.setAttachId(String.valueOf(attachIDs));
                    attachment.setModule(mid);
                    attachment.setAttachFile(oldFileName);
                    attachment.setAttachName(oldFileName);
                    attachment.setYm(ym);
                    attachment.setAttachSign(new Long(0));
                    attachment.setDelFlag((byte) 0);
                    attachment.setPosition((byte) 2);
                    attachment.setSize(Convert.convertFileSize(file.length()));
                    attachment.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    attachmentMapper.insertSelective(attachment);
                    attachmentListNew.add(attachment);
                }
            }
            StringBuilder attachmentIds = new StringBuilder();
            StringBuilder attachmentNames = new StringBuilder();
            attachmentListNew.forEach(attachment -> {
                attachmentIds.append(attachment.getAid()).append("@").append(attachment.getYm()).append("_").append(attachment.getAttachId()).append(",");
                attachmentNames.append(attachment.getAttachName()).append("*");
            });
            notify.setAttachmentId(attachmentIds.toString());
            notify.setAttachmentName(attachmentNames.toString());

            //处理正文word
            try {
                if (depPath != null) {
                    SysPara wordToHtmlOpen = sysParaMapper.querySysPara("WORD_TO_HTML_OPEN");

                    if("1".equals(wordToHtmlOpen.getParaValue())||System.getProperty("os.name").toLowerCase().startsWith("win")){
                        SysPara wordToHtmlAddress = sysParaMapper.querySysPara("WORD_TO_HTML_ADDRESS");
                        if(StringUtils.checkNull(wordToHtmlAddress.getParaValue())){
                            wordToHtmlAddress.setParaValue("http://127.0.0.1:8080");
                        }
                        Map<String,String> paraMap = new HashMap<>();
                        paraMap.put("url",wordToHtmlAddress.getParaValue()+"/ueditor/wordToHtml");
                        paraMap.put("filePath",depPath);
                        paraMap.put("module","doc2html");
                        JSONObject jsonObject = HttpClientUtil.uploadFile(paraMap);
                        if(jsonObject!=null&&"SUCCESS".equals(jsonObject.getString("state"))){
                            notify.setContent(jsonObject.getString("htmlContent"));
                        } else {
                            poi2Html(company, notify, depPath);
                        }

                    } else {
                        poi2Html(company, notify, depPath);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //获取表单内容
            if (flowHookMaps != null) {
                for (Map.Entry<Object, Object> entry : flowHookMaps.entrySet()) {
                    //标题
                    if (entry.getKey().equals("SUBJECT") && !StringUtils.checkNull(entry.getKey().toString())) {
                        notify.setSubject(entry.getValue().toString());
                    }
                    //简介
                    if (entry.getKey().equals("SUMMARY") && !StringUtils.checkNull(entry.getKey().toString())) {
                        notify.setSummary(entry.getValue().toString());
                    }
                    //发布人员
                    if (entry.getKey().equals("USER_ID") && !StringUtils.checkNull(entry.getKey().toString())) {
                        String strs = entry.getValue().toString();
                        String[] split = strs.split("\\|");
                        notify.setUserId(split[0]);
                    }
                }
            }
            //默认值
            notify.setTop("0");
            notify.setTopDays(0);
            notify.setFormat("0");
            notify.setPublish("0");
            notify.setDownload("1");
            notify.setHowRenind("0,1,");
            notifyMapper.updateNotify(notify);
        }
    }

    private void poi2Html(String company, Notify notify, String depPath) {
        Map map = WordHtml.wordToHtml(company, "ueditor", depPath);
        ArrayList<Attachment> attendList = (ArrayList<Attachment>) map.get("attendList");
        String strs = (String) map.get("content");
        for (Attachment attachment : attendList) {
            String key = attachment.getAttachId();
            attachmentMapper.insertSelective(attachment);
            String attUrl = "AID=" + attachment.getAid().toString() + "&MODULE=" + "ueditor" + "&COMPANY=" + company + "&YM=" + attachment.getYm() + "&ATTACHMENT_ID=" + attachment.getAttachId().toString() +
                    "&ATTACHMENT_NAME=" + attachment.getAttachName() + "&FILESIZE=" + attachment.getFileSize() + "\"";
            String url = "<img src=\"/xs?" + attUrl +
                    "title=\"\" " +
                    "_src=\"/xs?" + attUrl +
                    "alt=\"\"/>";
            strs = strs.replace("<img>" + key + "</img>", url);
        }
        strs = strs.replace("<span style=\"font-size", "<span style=\"font-family:&#39;方正仿宋_GBK&#39;;font-size");
        strs = strs.replace("border-bottom:thin solid red;border-left:thin solid black;border-right:thin solid black;border-top:thin solid black;", "");
        strs = strs.replace("<div style=\"width:", "<div style=\"")
                .replace("font-family:Calibri","font-family:方正仿宋_GBK");
        notify.setContent(strs);
    }
}
